﻿#region

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

#endregion

namespace Radovici.Ctrls
{
    public class YouTubePictures : ContentControl
    {
        private const string DefaultVideo = "abcdefjklmn";

        public static readonly DependencyProperty YouTubeVideoProperty =
            DependencyProperty.Register("YouTubeVideo", typeof (string), typeof (YouTubePictures),
                                        new PropertyMetadata(DefaultVideo, onYouTubeVideoChanged));

        public YouTubePictures()
        {
            Orientation = Orientation.Vertical;
        }

        public Orientation Orientation { get; set; }

        public string YouTubeVideo
        {
            get { return (string) GetValue(YouTubeVideoProperty); }
            set { SetValue(YouTubeVideoProperty, value); }
        }

        private static void onYouTubeVideoChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var pic = d as YouTubePictures;
            if (pic != null)
            {
                var tmpUrl = e.NewValue as string;
                if (!string.IsNullOrEmpty(tmpUrl))
                {
                    tmpUrl = tmpUrl.Replace("http://www.youtube.com/v/", string.Empty);
                }
                var panel = new StackPanel();
                panel.Orientation = pic.Orientation;
                for (int i = 1; i <= (string.IsNullOrEmpty(tmpUrl) ? 1 : 3); i++)
                {
                    var img = new Image();
                    img.Margin = new Thickness(4);
                    var uri = new Uri(string.Format("http://i.ytimg.com/vi/{0}/{1}.jpg", tmpUrl ?? DefaultVideo, i));
                    img.Source = new BitmapImage(uri);
                    panel.Children.Add(img);
                }
                pic.Content = panel;
            }
        }
    }
}